package com.liangchen.astools.ui.floatwindow

import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.Debug
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import android.view.*
import android.view.View.OnTouchListener
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.liangchen.astools.R
import com.liangchen.astools.utils.AsLog.i

class FloatWindowService : Service() {
    private val TAG = "FloatWindowService"
    var layoutParams = WindowManager.LayoutParams()
    var windowManager: WindowManager? = null
    var floatWindowView: View? = null
    var btnStart: TextView? = null
    @RequiresApi(api = Build.VERSION_CODES.M)
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        if (floatWindowView == null) {
            showFloatWindow()
        } else {
            Log.w(TAG, "exist! visble：" + floatWindowView!!.isShown)
            windowManager!!.removeViewImmediate(floatWindowView)
            floatWindowView = null
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder? {
        // TODO: Return the communication channel to the service.
        throw UnsupportedOperationException("Not yet implemented")
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private fun showFloatWindow() {
        if (Settings.canDrawOverlays(this)) {
            windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            floatWindowView = LayoutInflater.from(applicationContext).inflate(R.layout.layout_float_window, null)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE
            }
            layoutParams.format = PixelFormat.RGBA_8888
            layoutParams.gravity = Gravity.LEFT or Gravity.TOP
            layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            layoutParams.width = 500
            layoutParams.height = 100
            layoutParams.x = 300
            layoutParams.y = 300
            windowManager!!.addView(floatWindowView, layoutParams)
            floatWindowView?.setOnTouchListener(FloatOnTouchListener())
            btnStart = floatWindowView?.findViewById(R.id.tv_start)
            btnStart?.setOnClickListener(View.OnClickListener {
                btnStart?.setBackgroundResource(R.drawable.ic_home_black_24dp)
                i("cdgaslog", "start=+=1")
                val memoryInfo = Debug.MemoryInfo()
                Debug.getMemoryInfo(memoryInfo)
                val statsMap = memoryInfo.memoryStats
                val sb = StringBuffer()
                sb.append("""
    java: ${statsMap["summary.java-heap"]}
    
    """.trimIndent())
                sb.append("""
    native:${statsMap["summary.native-heap"]}
    
    """.trimIndent())
                sb.append("""
    code: ${statsMap["summary.code"]}
    
    """.trimIndent())
                sb.append("""
    stack: ${statsMap["summary.stack"]}
    
    """.trimIndent())
                sb.append("""
    graphics: ${statsMap["summary.graphics"]}
    
    """.trimIndent())
                sb.append("""
    other: ${statsMap["summary.private-other"]}
    
    """.trimIndent())
                sb.append("""
    system: ${statsMap["summary.system"]}
    
    """.trimIndent())
                sb.append("""
    total:: ${statsMap["summary.total-pss"]}
    
    """.trimIndent())
                sb.append("""
    swap: ${statsMap["summary.total-swap"]}
    
    """.trimIndent())
                i("cdgaslog", sb.toString())
            })
        }
    }

    private inner class FloatOnTouchListener : OnTouchListener {
        private var x = 0
        private var y = 0
        override fun onTouch(v: View, event: MotionEvent): Boolean {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    x = event.rawX.toInt()
                    y = event.rawY.toInt()
                }
                MotionEvent.ACTION_MOVE -> {
                    val nowX = event.rawX.toInt()
                    val nowY = event.rawY.toInt()
                    val movedX = nowX - x
                    val movedY = nowY - y
                    x = nowX
                    y = nowY
                    layoutParams.x = layoutParams.x + movedX
                    layoutParams.y = layoutParams.y + movedY

                    // 更新悬浮窗控件布局
                    windowManager!!.updateViewLayout(v, layoutParams)
                }
                else -> {
                }
            }
            return false
        }
    }
}